<?php
class Router {
	var $suffix	= '';
	var $request;
	var	$views;
	var	$apps;
	var $args		= array();
	var $segments	= array();
	
	function Router($uri, $suffix='') {
		$this->suffix	= $suffix;
		$this->request	= $uri;
		$this->explode_segments();
		
		$this->apps		= $this->setApps();
		$this->views	= $this->setViews();
	}
	
	function remove_suffix($url) {
		if  ($this->suffix == '') return $url;


		return preg_replace("|".preg_quote($this->suffix)."|", "", $url);
	}

	function explode_segments() {
		foreach(explode("/", $this->remove_suffix($this->request)) as $val) {
			$val = trim($val);
			if ($val != '') {
				$this->segments[] = $val;
			}
		}
	}
	
	function setApps() {
		if (count($this->segments) == 0) {
			return '/home/index' . APPS_EXT;
		}
		$apps		= array('');
		$segments	= $this->segments;
		while ($segment = array_shift($segments)) {

			if(file_exists(APPS_ABS . implode(SEPARATOR, $apps). SEPARATOR . $segment)) {
				$apps[] = $segment;
			} else if (file_exists(APPS_ABS . implode(SEPARATOR, $apps). SEPARATOR . $segment . APPS_EXT)){ 
				$apps[] = $segment . APPS_EXT;
			} else { 
				$this->args[] = mysql_escape_string($segment);
			}
		}
		if(is_dir(APPS_ABS . implode(SEPARATOR, $apps))){  
			return implode(SEPARATOR, $apps) . SEPARATOR. 'index'. APPS_EXT;
		} else { 
			return implode(SEPARATOR, $apps); 
		}
	}

	function setViews() {
		if (count($this->segments) == 0) {
			return  '/home/index' . VIEW_EXT;
		}
		
		$views		= array('');
		$segments	= $this->segments;

		while ($segment = array_shift($segments)) {
			if(file_exists(VIEW_ABS . implode(SEPARATOR, $views). SEPARATOR . $segment)) {
				$views[] = $segment;
			} else if (file_exists(VIEW_ABS . implode(SEPARATOR, $views). SEPARATOR . $segment . VIEW_EXT)){ 
				$views[] = $segment . VIEW_EXT;
			}
		}

		if(is_dir(VIEW_ABS . implode(SEPARATOR, $views))){  
			return implode(SEPARATOR, $views) . SEPARATOR. 'index'. VIEW_EXT;
		} else { 
			return implode(SEPARATOR, $views); 
		}
	}
}
?>